package com.hrh.selectsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrh.selectsystem.aop.MyJwtInterceptor;
import com.hrh.selectsystem.common.ErrorCode;
import com.hrh.selectsystem.constant.CommonConstant;
import com.hrh.selectsystem.exception.BusinessException;
import com.hrh.selectsystem.model.dto.file.MentorExcelImport;
import com.hrh.selectsystem.model.dto.mentor.MentorQueryRequest;
import com.hrh.selectsystem.model.dto.mentor.MentorUpdateRequest;
import com.hrh.selectsystem.model.entity.Mentor;
import com.hrh.selectsystem.model.entity.Student;
import com.hrh.selectsystem.model.vo.mentor.LoginMentorVO;
import com.hrh.selectsystem.model.vo.mentor.MentorByStudentVO;
import com.hrh.selectsystem.model.vo.mentor.MentorVO;
import com.hrh.selectsystem.service.MentorService;
import com.hrh.selectsystem.mapper.MentorMapper;
import com.hrh.selectsystem.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.stream.Collectors;

import static com.hrh.selectsystem.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author hetongxue
* @description 针对表【mentor(导师)】的数据库操作Service实现
* @createDate 2024-10-23 11:30:03
*/
@Service
@Slf4j
public class MentorServiceImpl extends ServiceImpl<MentorMapper, Mentor>
    implements MentorService{
    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "hrh";
    @Resource
    private MentorMapper mentorMapper;

    /**
     * 导师登录
     *
     * @param mentorAccount
     * @param mentorPassword
     * @param request
     * @return
     */
    @Override
    public LoginMentorVO mentorLogin(String mentorAccount, String mentorPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(mentorAccount, mentorPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (mentorPassword.length() < 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + mentorPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<Mentor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mentorAccount", mentorAccount);
        queryWrapper.eq("mentorPassword", encryptPassword);
        Mentor mentor = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (mentor == null) {
            log.info("mentor login failed, mentorAccount cannot match mentorPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 用户被禁用
        if (mentor.getStatus() == 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已被禁用");
        }
        // 3. 记录用户的登录态
        //request.getSession().setAttribute(USER_LOGIN_STATE, mentor);
        return this.getLoginMentorVO(mentor);
    }

    /**
     * 导师注销
     * @param request
     * @return
     */
    @Override
    public boolean mentorLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取当前登录导师
     * @param request
     * @return
     */
    @Override
    public Mentor getLoginMentor(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("token");
        // 获取用户id
        String userId = MyJwtInterceptor.getUserIdFromToken(token);
        // 查询用户
        Mentor mentor = mentorMapper.selectById(userId);
        if (mentor == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return mentor;
    }

    /**
     * 获取封装后导师信息(脱敏 & 登录后返回)
     * @param mentor
     * @return
     */
    private LoginMentorVO getLoginMentorVO(Mentor mentor) {
        if (mentor == null) {
            return null;
        }
        LoginMentorVO loginmentorVO = new LoginMentorVO();
        BeanUtils.copyProperties(mentor, loginmentorVO);
        return loginmentorVO;
    }

    /**
     * 获取封装后用户信息（脱敏）
     * @param mentor
     * @return
     */
    public MentorVO getMentorVO(Mentor mentor) {
        if (mentor == null) {
            return null;
        }
        MentorVO mentorVO = new MentorVO();
        BeanUtils.copyProperties(mentor, mentorVO);
        return mentorVO;
    }

    /**
     * 获取有名额导师列表
     * @param mentorQueryRequest
     * @return
     */
    @Override
    public Page<Mentor> getMentorHasQuota(MentorQueryRequest mentorQueryRequest, long current, long size) {
//        Wrapper<Mentor> queryWrapper = this.getQueryWrapper(mentorQueryRequest);
//
//        List<Mentor> mentorList = mentorMapper.selectList(queryWrapper);
//        mentorList = mentorList.stream().filter(mentor -> mentor.getMentorquota() > mentor.getSelectedquota()).collect(Collectors.toList());
//        return mentorList;
        // 创建分页对象
        Page<Mentor> page = new Page<>(current, size);

        // 构建查询条件
        Wrapper<Mentor> queryWrapper = this.getQueryWrapper(mentorQueryRequest);

        // 获取所有符合条件的导师总数
        long total = mentorMapper.selectCount(queryWrapper);
        page.setTotal(total);

        // 获取当前页符合条件的导师列表
        List<Mentor> mentorList = mentorMapper.selectPage(page, queryWrapper).getRecords();

        // 过滤出有名额的导师
        List<Mentor> hasQuotaMentorList = mentorList.stream()
                .filter(mentor -> mentor.getMentorquota() > mentor.getSelectedquota())
                .collect(Collectors.toList());

        // 设置分页结果
        page.setRecords(hasQuotaMentorList);

        return page;
    }

    /**
     * 提取更新请求的非空字段
     * @param mentorUpdateRequest
     * @param mentor
     * @return
     */
    @Override
    public Mentor notNullMentor(MentorUpdateRequest mentorUpdateRequest, Mentor mentor) {
        if (mentor == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (mentorUpdateRequest.getMentorname() != null && !mentorUpdateRequest.getMentorname().trim().isEmpty()) {
            mentor.setMentorname(mentorUpdateRequest.getMentorname());
        }
        if (mentorUpdateRequest.getMentorcollege() != null && !mentorUpdateRequest.getMentorcollege().trim().isEmpty()) {
            mentor.setMentorcollege(mentorUpdateRequest.getMentorcollege());
        }
        if (mentorUpdateRequest.getGender() != null && !mentorUpdateRequest.getGender().trim().isEmpty()) {
            mentor.setGender(mentorUpdateRequest.getGender());
        }
        if (mentorUpdateRequest.getMentorquota() != null) {
            mentor.setMentorquota(mentorUpdateRequest.getMentorquota());
        }
        if (mentorUpdateRequest.getMentoraccount() != null && !mentorUpdateRequest.getMentoraccount().trim().isEmpty()) {
            mentor.setMentoraccount(mentorUpdateRequest.getMentoraccount());
        }
        if (mentorUpdateRequest.getMentorpassword() != null && !mentorUpdateRequest.getMentorpassword().trim().isEmpty()) {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + mentorUpdateRequest.getMentorpassword()).getBytes());
            mentor.setMentorpassword(encryptPassword);
        }
        if (mentorUpdateRequest.getUseravatar() != null && !mentorUpdateRequest.getUseravatar().trim().isEmpty()) {
            mentor.setUseravatar(mentorUpdateRequest.getUseravatar());
        }
        if (mentorUpdateRequest.getUserrole() != null && !mentorUpdateRequest.getUserrole().trim().isEmpty()) {
            mentor.setUserrole(mentorUpdateRequest.getUserrole());
        }
        return mentor;
    }

    /**
     * 获取查询条件
     * @param mentorQueryRequest
     * @return
     */
    @Override
    public Wrapper<Mentor> getQueryWrapper(MentorQueryRequest mentorQueryRequest) {
        if (mentorQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = mentorQueryRequest.getId();
        String mentoraccount = mentorQueryRequest.getMentoraccount();
        String mentorname = mentorQueryRequest.getMentorname();
        String mentorcollege = mentorQueryRequest.getMentorcollege();
        String gender = mentorQueryRequest.getGender();
        String sortField = mentorQueryRequest.getSortField();
        String sortOrder = mentorQueryRequest.getSortOrder();
        QueryWrapper<Mentor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(mentoraccount), "mentoraccount", mentoraccount);
        queryWrapper.eq(StringUtils.isNotBlank(mentorcollege), "mentorcollege", mentorcollege);
        queryWrapper.eq(StringUtils.isNotBlank(gender), "gender", gender);
        queryWrapper.like(StringUtils.isNotBlank(mentorname), "mentorname", mentorname);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 从excel批量导入导师
     * @param mentorExcelList
     */
    @Override
    public void importMentorsFromExcel(List<MentorExcelImport> mentorExcelList) {
        mentorMapper.saveMentorBatch(mentorExcelList);
    }


}




